import json
import uuid
import time
from threading import Thread
from form import Ui_MainWindow
from PyQt5 import QtWidgets
import sys
import hashlib
import re
from datetime import datetime
import pyautogui as pg
import pyperclip as pc
from PyQt5.QtGui import QIcon
from dateutil.relativedelta import relativedelta


class WechatApp:

    def __init__(self):
        # self.switch = True

        pg.PAUSE = 1
        self.log = open('settings/logs.log', 'a', encoding='utf-8')
        self.app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(MainWindow)
        self.init()
        MainWindow.show()
        sys.exit(self.app.exec_())

    # 时段模式
    def time_mode(self):

        # 循环获取当前时间，如果为指定时间我们将调用main函数为女朋友发送晚安消息
        if datetime.now().isoweekday() <= 5:
            self.send_time = self.ui.textEdit.toPlainText().split(',')
        else:
            self.send_time = self.ui.textEdit_3.toPlainText().split(',')
        while True:
            if self.switch:

                hour = time.localtime()
                now_time = time.strftime("%H:%M:%S", hour)
                log_time = time.strftime("%Y-%m %H:%M:%S", hour)
                # print(f'\r{now_time}')
                # 如果时间为半夜12点，则给女朋友发消息
                if now_time in self.send_time:
                    print(now_time in self.send_time)
                    info = f'【时间】：{log_time}\n【接收人】:{",".join(self.current_nick)}\n【消息内容】:{",".join(self.current_msg)}\n----------------------------'
                    print(info)
                    name = self.current_nick
                    msg = self.current_msg
                    self.send_message(name, msg)
                    self.ui.textBrowser.append(info + '\n')
                    self.ui.textBrowser.ensureCursorVisible()  # 每次添加文本光标都在最后一行

                    self.log.write(info + '\n')
            else:
                break

    # 倒计时模式
    def second_mode(self):

        currrent_date = datetime.now()
        while True:
            if self.switch:
                n_date = datetime.now()
                now_date = n_date.strftime('%Y-%m-%d %H:%M:00')
                currrent_hour = int(self.ui.spinBox.text())
                currrent_mintues = int(self.ui.spinBox_3.text())
                send_date = (currrent_date + relativedelta(minutes=currrent_mintues,
                                                          hours=currrent_hour)).strftime('%Y-%m-%d %H:%M:00')
                # s_date = currrent_date.strftime(f'%Y-%m-%d %H:{(datetime.now().minute + currrent_mintues) % 60:02d}')

                self.ui.groupBox.setTitle(f'\r当前时间：{now_date} 发送时间：{send_date}')
                self.ui.textBrowser.ensureCursorVisible()  # 每次添加文本光标都在最后一行

                print(f'\r当前时间：{now_date} 消息发送时间：{send_date}', end='')

                # 如果当前时间等于发消息时间则开始发消息
                if now_date == send_date:
                    currrent_date = datetime.now()
                    name = self.current_nick
                    msg = self.current_msg
                    self.send_message(name, msg)
                    info = f'【时间】：{now_date}\n【接收人】:{",".join(self.current_nick)}\n【消息内容】:{",".join(self.current_msg)}\n----------------------------'
                    self.ui.textBrowser.append(info + '\n')
                    self.ui.textBrowser.ensureCursorVisible()  # 每次添加文本光标都在最后一行

                    self.log.writelines(info)
                    print('\n', info)
            else:
                break
            # print(f'\r', end='')

            time.sleep(1)

    # 加载配置数据
    def init(self):

        self.app.setWindowIcon(QIcon('./settings/logo.png'))
        self.file = open('settings/config.json', 'r', encoding='utf-8')
        self.config = json.loads(self.file.read())
        nick = self.config['nick']
        content = self.config['content']
        hour = self.config['hour']
        minutes = self.config['minutes']
        workday = self.config['workday']
        unworkday = self.config['unworkday']

        # 单选框数据加载
        self.ui.comboBox.addItem('所有人')
        self.ui.comboBox.addItems(nick)

        self.ui.comboBox_2.addItem('所有消息')
        self.ui.comboBox_2.addItems(content)

        self.ui.comboBox_3.addItems(['分钟模式', '时段模式'])
        self.ui.comboBox.setCurrentText('所有人')
        self.ui.comboBox_2.setCurrentText('所有消息')
        self.ui.comboBox_2.setCurrentText('所有消息')
        self.ui.spinBox.setRange(0, 24)
        self.ui.spinBox.setValue(int(hour))
        self.ui.spinBox_3.setRange(0, 60)
        self.ui.spinBox_3.setValue(int(minutes))

        self.ui.textEdit.setText(','.join(workday))
        self.ui.textEdit_3.setText(','.join(unworkday))
        self.ui.textEdit_4.setText(','.join(nick))
        self.ui.textEdit_8.setText(','.join(content))

        # 开始运行按钮设置绑定事件
        self.ui.pushButton_2.clicked.connect(lambda: self.start_thread(self.start))
        # 关闭运行按钮设置绑定事件
        # self.ui.pushButton.clicked.connect(lambda: self.start_thread(self.stop))
        self.ui.pushButton.clicked.connect(self.stop)

        key = self.config['key']
        self.ui.textEdit_9.setText(key)
        if self.verification(self.ui.textEdit_9.toPlainText()):
            self.switch = True

        else:
            self.switch = False
            uid = str(uuid.uuid1()).split('-')[-1]
            pattern = re.compile('\d+')
            uid = re.search(pattern, uid).group()
            self.ui.groupBox.setTitle(f'软件已禁用，您的设备码：{uid} 联系微信：init3323解锁')
        self.set_hide()

    def start_thread(self, func):
        thread = Thread(target=func)
        thread.start()

    def send_message(self, name, msg):
        # 打开微信
        pg.hotkey('ctrl', 'alt', 'w')
        time.sleep(1)
        for user, message in zip(name, msg):
            print(user, message)
            pg.hotkey('ctrl', 'f')

            # 找到消息发送对象
            pc.copy(user)
            pg.hotkey('ctrl', 'v')
            pg.press('enter')

            # 发送消息
            pc.copy(message)
            pg.hotkey('ctrl', 'v')
            pg.press('enter')

        # 隐藏微信
        pg.hotkey('ctrl', 'alt', 'w')

    def stop(self):
        self.file.close()
        self.ui.textBrowser.clear()
        self.ui.textBrowser.append('结束运行'.center(45, '*'))
        self.switch = False

    def start(self):
        key = self.ui.textEdit_9.toPlainText()
        password = self.verification(key)
        print(password)
        self.set_hide()
        # self.ui.textBrowser.clear()
        # 如果激活码正确 则可以使用功能
        if password:
            self.ui.textBrowser.append('开始运行'.center(45, '*'))
            self.ui.textBrowser.append(f'{self.ui.comboBox_3.currentText()}'.center(30, '-'))
            self.switch = True
            self.current_nick = self.ui.comboBox.currentText()
            self.current_msg = self.ui.comboBox_2.currentText()

            mode = self.ui.comboBox_3.currentText()
            hour = self.ui.spinBox.text()
            minutes = self.ui.spinBox_3.text()
            workday = self.ui.textEdit.toPlainText().split(',')
            unworkday = self.ui.textEdit_3.toPlainText().split(',')
            nick = self.ui.textEdit_4.toPlainText().split(',')
            content = self.ui.textEdit_8.toPlainText().split(',')

            if self.current_nick == '所有人':
                self.current_nick = self.config['nick']
            else:
                self.current_nick = [self.current_nick]
                self.msg_index = self.config['content'][self.ui.comboBox.currentIndex() - 1]
                self.current_msg = [self.msg_index]
                self.ui.comboBox_2.setCurrentText(self.msg_index)
            if self.current_msg == '所有消息':
                self.current_msg = self.config['content']
            else:
                self.current_msg = [self.current_msg]
            config = {
                "nick": nick,
                "content": content,
                "mode": mode,
                "hour": hour,
                "minutes": minutes,
                "key": self.ui.textEdit_9.toPlainText(),
                "workday": workday,
                "unworkday": unworkday
            }
            with open('settings/config.json', 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=4)
                f.close()
            if mode == '时段模式':
                self.ui.groupBox.setTitle('时段模式')
                self.time_mode()
            elif mode == '分钟模式':
                self.second_mode()
            # print(current_nick, current_msg, mode, hour, minutes, workday, unworkday, nick, content)
        else:
            self.ui.groupBox.setTitle('激活码错误！联系微信：init3323解锁')

    # 控件禁用状态
    def set_hide(self):
        self.ui.comboBox.setEnabled(self.hide)
        self.ui.comboBox_2.setEnabled(self.hide)
        self.ui.comboBox_3.setEnabled(self.hide)
        self.ui.textEdit.setEnabled(self.hide)
        self.ui.textEdit_4.setEnabled(self.hide)
        self.ui.textEdit_3.setEnabled(self.hide)
        self.ui.textEdit_8.setEnabled(self.hide)
        self.ui.spinBox.setEnabled(self.hide)
        self.ui.spinBox_3.setEnabled(self.hide)
        self.ui.pushButton.setEnabled(self.hide)

    def verification(self, pwd):
        uid = str(uuid.uuid1()).split('-')[-1]
        pattern = re.compile('\d+')
        uid = re.search(pattern, uid).group()
        key = int(uid) * 38 + 85 - 28

        result = hashlib.md5(str(key).encode()).hexdigest()
        if pwd == result:
            self.hide = True
            return True
        else:
            self.hide = False
            return False


if __name__ == '__main__':
    wx = WechatApp()
